define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxPreestimateDataSearch";

    var fxPreestimateDataSearchFormHtml = sysPath + "/views/fxPreestimateDataSearchForm.html";
    var getFxPreestimateResultController = function () {
        return getServer() + "/fx/fxPreestimateResults";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        createFxPreestimateDataSearchGrid();
    };


    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
        require(["jquery", "Date", "DateCN", "css!DateCss"], function ($) {
            $("#yearStart").datetimepicker({
                //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
                language: "cn",
                //输出格式化
                format: 'yyyy',
                //直接选择‘今天’
                todayBtn: true,
                weekStart: 1,
                // 设置最精确的时间选择视图
                startView: 4,
                //设置最精确的时间选择视图
                minView: 4,
//              minView: 'month',
                //高亮当天日期
                todayHighlight: true,
                //选择完毕后自动关闭
                autoclose: true
            });


            $("#yearEnd").datetimepicker({
                //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
                language: "cn",
                //输出格式化
                format: 'yyyy',
                weekStart: 1,
                // 设置最精确的时间选择视图
                startView: 4,
                //直接选择‘今天’
                todayBtn: true,
                //设置最精确的时间选择视图
                minView: 4,
                //minView: 'month',
                //高亮当天日期
                todayHighlight: true,
                //选择完毕后自动关闭
                autoclose: true
            });

        })
    };
    var queryBtnBind = function () {
    	$("#yearStart").change(function () {
            if ($("#yearStart").val() != "" && $("#yearEnd").val() != "") {
                if ($("#yearStart").val() > $("#yearEnd").val()) {
                    Util.alert("开始年度必须小于等于结束年度", function () {
                        $("#yearStart").val("");
                        $("#yearEnd").val("");
                    });
                    return;
                }
            }
        });
        $("#yearEnd").change(function () {
            if ($("#yearStart").val() != "" && $("#yearEnd").val() != "") {
                if ($("#yearStart").val() > $("#yearEnd").val()) {
                    Util.alert("开始年度必须小于等于结束年度", function () {
                        $("#yearStart").val("");
                        $("#yearEnd").val("");
                    });
                    return;
                }
            }
        });
        $("#btnSearch").click(function () {
            createFxPreestimateDataSearchGrid();
        });
        $("#btnReset").click(function () {
            $("#workspaceCondition").val("");
            $("#yearStart").val("");
            $("#yearEnd").val("");
            $("#magnitudeStart").val("");
            $("#magnitudeEnd").val("");
        });
    };
    var createFxPreestimateDataSearchGrid = function () {
        $("#fxPreestimateDataSearchGrid").datagrid({
            url: getFxPreestimateResultController() + "/queryFxPreestimateResults",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            rownumbers: true,
            columns: [[
                //{field: "ck", checkbox: true},
                {
                    field: 'workspace',
                    title: '工作区名称',
                    width: '11%',
                    align: 'center',
                    /*formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_editFxPreestimateResult(\'' + rowData.id + '\');"> ' + rowData.workspace + ' </a> '
                    }*/
                },
                {
                    field: 'year',
                    title: '年度',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'longitude',
                    title: '设定地震经度',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'latitude',
                    title: '设定地震纬度',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'location',
                    title: '宏观位置',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'magnitude',
                    title: '震级',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'disasterArea',
                    title: '灾区面积/平方公里',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'disasterAreaPopulation',
                    title: '灾区人口/万人',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'disasterAreaGdp',
                    title: '灾区GDP/亿元',
                    width: '11%',
                    align: 'center',
                },
            ]],
            toolbar: [/*{
                iconCls: 'fa fa-plus-circle',
                text: "添加",
                handler: function () {
                    addFxPreestimateResult();
                }
            },*/ {
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportForm();
                }
            }/*, {
                iconCls: 'fa fa-trash-o',
                text: "删除",
                handler: function () {
                    deleteFxPreestimateResult();
                }
            }*/],
            queryParams: {
                workspace: $("#workspaceCondition").val(),
                yearStart: $("#yearStart").val(),
                yearEnd: $("#yearEnd").val(),
                magnitudeStart: $("#magnitudeStart").val(),
                magnitudeEnd: $("#magnitudeEnd").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
    var formValidator = function () {
        $("#fxPreestimateDataSearchForm").validate({
            rules: {
                workspace: {
                    required: true,
                },
                year: {
                    required: true,
                },
                longitude: {
                    required: true,
                },
                latitude: {
                    required: true,
                },
                magnitude: {
                    required: true,
                },
                location: {
                    required: true,
                },
                disasterArea: {
                    required: true,
                },
                disasterAreaPopulation: {
                    required: true,
                },
                disasterAreaGdp: {
                    required: true,
                },
                deathNum: {
                    required: true,
                },
                deathNumBefore: {
                    required: true,
                },
                deathNumAfter: {
                    required: true,
                },
                injuryNum: {
                    required: true,
                },
                injuryNumAfter: {
                    required: true,
                },
                urgentArrangeNum: {
                    required: true,
                },
                unitRescueNum: {
                    required: true,
                },
                medicalRescueNum: {
                    required: true,
                },
                tentNum: {
                    required: true,
                },
                economicLoss: {
                    required: true,
                },
                emergencyTeam: {
                    required: true,
                },
            },
            messages: {
                workspace: {
                    required: "工作区名称不允许为空!",
                },
                year: {
                    required: "年度不允许为空!",
                },
                longitude: {
                    required: "设定地震经度不允许为空!",
                },
                latitude: {
                    required: "设定地震纬度不允许为空!",
                },
                magnitude: {
                    required: "震级不允许为空!",
                },
                location: {
                    required: "宏观位置不允许为空!",
                },
                disasterArea: {
                    required: "灾区面积/平方公里不允许为空!",
                },
                disasterAreaPopulation: {
                    required: "灾区人口/万人不允许为空!",
                },
                disasterAreaGdp: {
                    required: "灾区GDP/亿元不允许为空!",
                },
                deathNum: {
                    required: "预估死亡人数（人）不允许为空!",
                },
                deathNumBefore: {
                    required: "预估死亡数（修正前）不允许为空!",
                },
                deathNumAfter: {
                    required: "预估死亡人数（修正后）不允许为空!",
                },
                injuryNum: {
                    required: "预估受伤人数不允许为空!",
                },
                injuryNumAfter: {
                    required: "预估受伤人数（修正后）不允许为空!",
                },
                urgentArrangeNum: {
                    required: "需紧急安置数不允许为空!",
                },
                unitRescueNum: {
                    required: "救援部队队伍（人）不允许为空!",
                },
                medicalRescueNum: {
                    required: "医疗救援(人)不允许为空!",
                },
                tentNum: {
                    required: "预估帐篷总数不允许为空!",
                },
                economicLoss: {
                    required: "预估经济损失（亿元）不允许为空!",
                },
                emergencyTeam: {
                    required: "需应急处置队伍（人）不允许为空!",
                },
            }
        });
    };
    var getFxPreestimateResult = function (id) {
        $.ajax({
            url: getFxPreestimateResultController() + "/" + id,
            type: "get",
            success: function (data) {
                Tool.deserialize("fxPreestimateDataSearchForm", data);
            }
        });
    };

    var addFxPreestimateResult = function () {
        var slidebar = Util.slidebar({
            url: fxPreestimateDataSearchFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                $("#saveBtn").on("click", function () {
                    if ($("#fxPreestimateResultForm").valid()) {
                        var data = Tool.serialize("fxPreestimateDataSearchForm");
                        $.ajax({
                            url: getFxPreestimateResultController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxPreestimateDataSearchGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    // 导出
    var exportForm = function () {
        let workspace = $("#workspaceCondition").val();
        let yearStart = $("#yearStart").val();
        let yearEnd = $("#yearEnd").val();
        let magnitudeStart = $("#magnitudeStart").val();
        let magnitudeEnd = $("#magnitudeEnd").val();
        window.location.href = getFxPreestimateResultController() + "/export?workspace=" + workspace + "&yearStart="
            + yearStart + "&yearEnd=" + yearEnd + "&magnitudeStart=" + magnitudeStart + "&magnitudeEnd=" + magnitudeEnd;
    };

    window._editFxPreestimateResult = function (fxPreestimateResultId) {
        var slidebar = Util.slidebar({
            url: fxPreestimateDataSearchFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                getFxPreestimateResult(fxPreestimateResultId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxPreestimateDataSearchForm").valid()) {
                        var data = Tool.serialize("fxPreestimateDataSearchForm");
                        $.ajax({
                            url: getFxPreestimateResultController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxPreestimateDataSearchGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteFxPreestimateResult = function () {
        var rows = $("#fxPreestimateDataSearchGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxPreestimateResultController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxPreestimateDataSearchGrid();
                }
            });
        }, function () {
            return;
        });

    };

    return {
        init: init
    };
});
